package com.thehun.mickeymall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.thehun.common.constant.AuthServerConstant;
import com.thehun.common.utils.HttpUtils;
import com.thehun.common.utils.R;
import com.thehun.common.vo.MemberRespVo;
import com.thehun.mickeymall.auth.feign.MemberFeignService;
import com.thehun.mickeymall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 根据code换取token
        Map<String,String> map = new HashMap<>();
        map.put("client_id", "655032858");
        map.put("client_secret", "2e761145b05bd4bd97448b934793abb7");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.mickeymall.com/oauth2.0/weibo/success");
        map.put("code", code);
        Map<String, String> headers = new HashMap<>();
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, null, map);

        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了 Access Token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            // 相当于我们知道了当前是那个用户
            // 1.如果用户是第一次进来 自动注册进来(为当前社交用户生成一个会员信息 以后这个账户就会关联这个账号)
            R login = memberFeignService.oauthlogin(socialUser);
            if(login.getCode() == 0){
                MemberRespVo data = login.getData("data" ,new TypeReference<MemberRespVo>() {});

                log.info("\n欢迎 [" + data.getUsername() + "] 使用社交账号登录");

                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            } else {
                return "redirect:http://auth.mickeymall.com/login.html";
            }
        } else {
            return "redirect:http://auth.mickeymall.com/login.html";
        }
        return "redirect:http://mickeymall.com";
    }
}
